package com.qiantu.api.db;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.qiantu.api.R;
import com.qiantu.api.db.database.LocalDataBase;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.db.greendao.FloorBeanDao;
import com.qiantu.api.entity.SceneBean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.qiantu.api.entity.RoomBean.ROOM_COMMON_SERIALNO;

/**
 * Created by cjc on 2019/5/7
 */
public class LLFloorDBManager {

    private final String TAG = "LLFloorDBManager";
    private volatile static LLFloorDBManager instance = null;
    private final static Object object = new Object();
    private final FloorBeanDao mFloorBeanDao;
    private Context context;

    private LLFloorDBManager(Context context) {
        this.context = context;
        mFloorBeanDao = LocalDataBase.getInstance().getDaoSession(context).getFloorBeanDao();
    }

    public static LLFloorDBManager getInstance(Context context) {
        if (instance == null) {
            synchronized (object) {
                if (instance == null) {
                    instance = new LLFloorDBManager(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    public void clearFromDB() {
        mFloorBeanDao.deleteAll();
    }

    /**
     * 从服务器更新楼层数据
     *
     * @param floorList
     */
    public void putInTx(List<FloorBean> floorList) {
        LocalDataBase.getInstance().getDaoSession(context).runInTx(() -> {
            for (FloorBean floor : floorList) {
                put(floor);
            }
        });
    }

    /**
     * 从服务器更新楼层数据
     *
     * @param floorList
     */
    public void refreshAllFloorsTx(List<FloorBean> floorList, HandleListener listener) {
        LocalDataBase.getInstance().getDaoSession(context).runInTx(() -> {
            clearFromDB();
            if(floorList == null){
                return;
            }
            Log.i("lzxzx", "refreshAllFloorsTx:" + floorList.size());
            for (FloorBean floor : floorList) {
                mFloorBeanDao.save(floor);
            }
        });
    }

    /**
     * 保存或者更新楼层
     *
     * @param floor
     */
    public void put(FloorBean floor) {
        if (floor == null)
            return;
        String floorSerialNo = floor.getFloorSerialNo();
        if (floorSerialNo != null && !TextUtils.isEmpty(floorSerialNo)) {
            FloorBean oldFloor = mFloorBeanDao.queryBuilder()
                    .where(FloorBeanDao.Properties.FloorSerialNo.eq(floorSerialNo))
                    .unique();
            if (oldFloor != null) {
                floor.setId(oldFloor.getId());
            }
        }
        mFloorBeanDao.save(floor);
    }

    /**
     * 通过floorNo获取房间
     *
     * @param floorSerialNo
     * @return
     */
    public FloorBean getFloorByFloorSerialNo(String floorSerialNo) {
        if(TextUtils.isEmpty(floorSerialNo)){
            return null;
        }
        return mFloorBeanDao.queryBuilder().where(FloorBeanDao.Properties.FloorSerialNo.eq(floorSerialNo)).unique();
    }

    /**
     * 删除楼层
     *
     * @param floor
     */
    public void remove(FloorBean floor) {
        if (floor == null)
            return;
        FloorBean tbFloor = mFloorBeanDao.queryBuilder()
                .where(FloorBeanDao.Properties.FloorSerialNo.eq(floor.getFloorSerialNo()))
                .unique();
        if (tbFloor != null) {
            mFloorBeanDao.delete(tbFloor);
        }
    }

    /**
     * 删除默认楼层
     */
    public void removeDefaultFloor() {
        FloorBean tbFloor = mFloorBeanDao.queryBuilder()
                .where(FloorBeanDao.Properties.Type.eq(1))
                .unique();
        if (tbFloor != null) {
            mFloorBeanDao.delete(tbFloor);
        }
    }

    /**
     * 获得本地所有楼层(默认楼层不显示)
     *
     * @return
     */
    public List<FloorBean> getAll() {
        List<FloorBean> floors = mFloorBeanDao.queryBuilder()
                .orderAsc(FloorBeanDao.Properties.Sort)
                .orderAsc(FloorBeanDao.Properties.CreateTime)
                .list();
        //只有一个默认楼层返回，有多个楼层，过滤掉默认楼层
        if(floors != null && floors.size() > 1){
            for(FloorBean floorBean : floors){
                if(floorBean.getType() == 1){
                    floors.remove(floorBean);
                    break;
                }
            }
        }
        return floors;
    }

    /**
     * 带房间信息
     * @return
     */
    public List<FloorBean> getNotEmptyRoomFloors() {
        List<FloorBean> floors = new ArrayList<>();
        //添加通用
        FloorBean commonFloor = new FloorBean();
        RoomBean commonRoom = new RoomBean();
        commonRoom.setRoomName(context.getString(R.string.common));
        commonRoom.setRoomSerialNo(ROOM_COMMON_SERIALNO);
        commonFloor.addRoom(commonRoom);
        commonFloor.setId(RoomBean.COMMON_ROOM_ID);
        floors.add(commonFloor);
        if(getAll() != null && getAll().size() > 0){
            floors.addAll(getAll());
        }
        Iterator<FloorBean> it = floors.iterator();
        while (it.hasNext()) {
            FloorBean floor = it.next();
            List<RoomBean> rooms = null;
            if(!TextUtils.isEmpty(floor.getFloorSerialNo())){
                rooms = LLRoomDBManager.getInstance(context).getRoomListByFloorSerialNo(floor.getFloorSerialNo());
                RoomBean roomBean = new RoomBean();
                roomBean.setRoomName(floor.getFloorName());
                roomBean.setRoomSerialNo(floor.getFloorSerialNo());
                roomBean.setFloorSerialNo(floor.getFloorSerialNo());
                roomBean.setFloorName(floor.getFloorName());
                rooms.add(0,roomBean);
                if(rooms == null || rooms.size() == 0){
                    it.remove();
                }else{
                    floor.setRooms(rooms);
                }
            }
        }
        return floors;
    }

    /**
     * 带房间信息
     * @return
     */
    public List<FloorBean> getAllDetail() {
        List<FloorBean> floors = getAll();
        for(FloorBean floorBean : floors){
            List<RoomBean> rooms = null;
            if(!TextUtils.isEmpty(floorBean.getFloorSerialNo())){
                rooms = LLRoomDBManager.getInstance(context).getRoomListByFloorSerialNo(floorBean.getFloorSerialNo());
            }
            floorBean.setRooms(rooms);
        }
        return floors;
    }

    public List<FloorBean> getAllDetailWithCommonRoom(int type) {
        List<FloorBean> result = new ArrayList<>();
        FloorBean commonFloor = new FloorBean();
        RoomBean commonRoom = new RoomBean();
        commonRoom.setRoomName(context.getString(R.string.common));
        commonRoom.setRoomSerialNo(ROOM_COMMON_SERIALNO);
        commonRoom.setSceneSize(LLSceneDBManager.getInstance(context).getCommonSceneSize());
        commonRoom.setDeviceSize(LLDeviceDBManager.getInstance(context).getCommonDeviceSize());
        commonFloor.addRoom(commonRoom);
        result.add(commonFloor);
        result.addAll(getNotEmptyRoomFloorsWithSceneDeviceCount(type));
        return result;
    }

    /**
     * 带房间信息
     * @return
     */
    public List<FloorBean> getNotEmptyRoomFloorsWithSceneDeviceCount(int type) {
        List<FloorBean> floors = getAll();
        Iterator<FloorBean> it = floors.iterator();
        while (it.hasNext()) {
            FloorBean floor = it.next();
            List<RoomBean> rooms = null;
            if(TextUtils.isEmpty(floor.getFloorSerialNo())){
                rooms = LLRoomDBManager.getInstance(context).getAll();
            }else{
                rooms = LLRoomDBManager.getInstance(context).getRoomListByFloorSerialNo(floor.getFloorSerialNo());
            }
            if(rooms == null || rooms.size() == 0){
                if(type != 1){
                    rooms = new ArrayList<>();
                    floor.setRooms(rooms);
                }else{
                    it.remove();
                }
            }else{
                for(RoomBean room : rooms){
                    room.setSceneSize(LLSceneDBManager.getInstance(context).getSceneSizeByRoom(room.getRoomSerialNo()));
                    room.setDeviceSize(LLDeviceDBManager.getInstance(context).getDeviceSizeByRoom(room.getRoomSerialNo()));
                }
                floor.setRooms(rooms);
            }
        }
        return floors;
    }

    /**
     * 获得楼层信息
     *
     * @return
     */
    public FloorBean get(String floorSerialNo) {
        return mFloorBeanDao.queryBuilder()
                .where(FloorBeanDao.Properties.FloorSerialNo.eq(floorSerialNo))
                .unique();
    }

    /**
     * 获得楼层信息
     *
     * @return
     */
    public List<FloorBean> getFloorByHouseSerialNo(String houseSerialNo) {
        if(TextUtils.isEmpty(houseSerialNo)){
            return null;
        }
        return mFloorBeanDao.queryBuilder()
                .where(FloorBeanDao.Properties.HouseSerialNo.eq(houseSerialNo))
                .orderDesc(FloorBeanDao.Properties.Type)
                .orderAsc(FloorBeanDao.Properties.Sort)
                .orderAsc(FloorBeanDao.Properties.CreateTime)
                .list();
    }
}
